package com.umakr.ax.app.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.umakr.ax.app.vo.MsgParamsVO;
import com.umakr.ax.common.enm.AttentionFrom;
import com.umakr.ax.common.model.Msg;
import com.umakr.ax.common.model.RadioStation;
import com.umakr.ax.common.service.MsgService;
import com.umakr.ax.common.service.RadioStationFollowerService;
import com.umakr.ax.common.service.RadioStationService;
import com.umakr.ax.common.service.UserScoreService;
import com.umakr.ax.utils.FormatPhotoUrlUtil;
import com.umakr.ax.xf.Mp3ConvertorAndXfTransformService;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Date;
import java.util.Map;

/**
 * Created by Mikey on 2018/1/2.
 * @author Mikey
 */
@Service
public class MsgAppService {
    protected final Log logger = LogFactory.getLog(this.getClass());

    @Autowired
    Environment env;

    @Autowired
    MsgService msgService;
    @Autowired
    RadioStationService radioStationService;

    @Autowired
    UserScoreService userScoreService;

    @Autowired
    RadioStationFollowerService radioStationFollowerService;

    @Autowired
    Mp3ConvertorAndXfTransformService mp3ConvertorAndXfTransformService;

    private static final String MSGTYPE_VOICE = "voice";
    private static final String MSGTYPE_TEXT = "text";
    private static final String MSGTYPE_IMAGE = "image";
    private static final String MSGTYPE_VIDEO = "video";
    private static final String MSGTYPE_GEOMETRY = "geometry";
    private static final Integer MSGTYPE_IMAGE_VALUE = 2;
    private static final Integer MSGTYPE_VIDEO_VALUE = 4;
    private static final Integer MSGTYPE_GEOMETRY_VALUE = 3;

    private void saveVoiceMsg(RadioStation radioStation,
                              MsgParamsVO paramsVO,
                              MultipartFile multipartFile){
        String basePath = env.getProperty("media.dir");
        long time = System.currentTimeMillis();
        if(!multipartFile.isEmpty() && radioStation!=null){

            String fileAbDir = "audio"+File.separator+radioStation.getId()+File.separator+paramsVO.getUserId();
            String uploadPath = basePath + File.separator + fileAbDir;
            File upFileDir = new File(uploadPath);
            if (!upFileDir.isDirectory()) {
                upFileDir.mkdirs();
            }
            String filePath = uploadPath + File.separator + time + ".aac";

            File outPath = new File(filePath);

            try( BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outPath))) {
                IOUtils.copyLarge(multipartFile.getInputStream(),out);
                out.flush();
                mp3ConvertorAndXfTransformService.handlerMsg(filePath, radioStation.getId(), paramsVO.getUserId(), new Mp3ConvertorAndXfTransformService.MsgCall() {
                    @Override
                    public void result(String convertedMp3Path, String xfTransformResult, String errMsg) {


                        try {
                            Msg msg = new Msg();
                            msg.setMsgTime(new Date());
                            msg.setMsgDirect(0);
                            msg.setRadioLen((int)Float.parseFloat(paramsVO.getVoiceLen()+""));
                            msg.setMessageFrom(1);
                            msg.setRsId(radioStation.getId());
                            msg.setUserId(paramsVO.getUserId());

                            //语音类型
                            msg.setMsgContentType(1);
                            //互动类型
                            msg.setMsgType(0);
                            //待审
                            msg.setStatus(0);
                            msg.setMsgAttachmentAddr(convertedMp3Path);
                            msg.setMsgTxtContent(xfTransformResult);
                            setLngLatDirect(paramsVO.getLongitude(),paramsVO.getLatitude(),paramsVO.getDirection(),paramsVO.getSpeed(),msg);
                            msg.setPositionName(paramsVO.getPositionName());
                            msg.setDelStatus(0);
                            msgService.update(msg);
                        } catch (Exception e) {
                            logger.error(e.getMessage());
                        }
                    }
                });
                }catch (Exception e){

                logger.debug(e);
            }
        }
    }
    public Map<String,Object> sendMsgToRs(MsgParamsVO paramsVO,
                                          MultipartFile multipartFile){
        String avatar = env.getProperty("oss.img.path");
        if(StringUtils.isNotEmpty(paramsVO.getRsCode()) || paramsVO.getRsId() != null){
            EntityWrapper<RadioStation> radioStationEntityWrapper = new EntityWrapper<>();
            if(paramsVO.getRsId() != null) {
                radioStationEntityWrapper.eq("id", paramsVO.getRsId());
            }else if(StringUtils.isNotEmpty(paramsVO.getRsCode())){
                radioStationEntityWrapper.eq("rs_code",paramsVO.getRsCode());
            }
            RadioStation radioStation =  radioStationService.selectOne(radioStationEntityWrapper);
            if(radioStation == null) {
                return  ImmutableMap.of("errorCode",0,"msg","电台不存在。");
            }

            //音频文件上传保存
            if(MSGTYPE_VOICE.equals(paramsVO.getMsgType())){
                saveVoiceMsg(radioStation,paramsVO,multipartFile);
            }else if(MSGTYPE_TEXT.equals(paramsVO.getMsgType())){
                saveTextMsg(radioStation,paramsVO);
            }else {
                saveOtherMsg(radioStation,paramsVO);
            }
            Map<String,Object> map = Maps.newHashMap();
            map.put("title",radioStation.getRsName());
            map.put("rsId",radioStation.getId());
            map.put("rsCode",radioStation.getRsCode());
            map.put("avatar", FormatPhotoUrlUtil.formatString(avatar,radioStation.getRsLogo()));
            //增加积分
            //互动时增加积分
            userScoreService.autoAddUpScore(paramsVO.getUserId(),radioStation.getId(),1);
            //识别时自动关注。 3 此种情况，前台未传入rsId。以此判断是否为识别时自动关注。
            //聊天时自动关注。 0此种情况，前台传入rsId。以此判断是否为聊天时自动关注。
            radioStationFollowerService.autoAttention(paramsVO.getUserId(),radioStation.getId(),
                    paramsVO.getRsCode() == null ? AttentionFrom.CHAT : AttentionFrom.AUTO_RECOGNIZE);
            return ImmutableMap.of("errorCode",1,"msg","发送成功。","data",map);
        }
        return null;
    }

    private void saveOtherMsg(RadioStation radioStation, MsgParamsVO paramsVO) {
        Msg msg = new Msg();
        msg.setMsgTime(new Date());
        msg.setMsgDirect(0);
        msg.setMessageFrom(1);
        msg.setRsId(radioStation.getId());
        msg.setUserId(paramsVO.getUserId());

        Integer msgTp = 2;
        if(MSGTYPE_IMAGE.equals(paramsVO.getMsgType())){ msgTp = MSGTYPE_IMAGE_VALUE;}
        if(MSGTYPE_VIDEO.equals(paramsVO.getMsgType())){ msgTp = MSGTYPE_VIDEO_VALUE;}
        if(MSGTYPE_GEOMETRY.equals(paramsVO.getMsgType())){  msgTp = MSGTYPE_GEOMETRY_VALUE;}

        //语音类型
        msg.setMsgContentType(msgTp);
        //互动类型
        msg.setMsgType(0);
        //待审
        msg.setStatus(0);
        msg.setMsgAttachmentAddr(paramsVO.getContent());
        setLngLatDirect(paramsVO.getLongitude(),paramsVO.getLatitude(),paramsVO.getDirection(),paramsVO.getSpeed(),msg);
        msg.setPositionName(paramsVO.getPositionName());
        msg.setDelStatus(0);
        msgService.update(msg);
    }

    private void saveTextMsg(RadioStation radioStation, MsgParamsVO paramsVO) {
        Msg msg = new Msg();
        msg.setMsgTime(new Date());
        msg.setMsgDirect(0);
        msg.setMessageFrom(1);
        msg.setRsId(radioStation.getId());
        msg.setUserId(paramsVO.getUserId());
        msg.setMsgContentType(0);
        //互动类型
        msg.setMsgType(0);
        //待审
        msg.setStatus(0);
        msg.setMsgAttachmentAddr(paramsVO.getContent());
        setLngLatDirect(paramsVO.getLongitude(),paramsVO.getLatitude(),paramsVO.getDirection(),paramsVO.getSpeed(),msg);
        msg.setPositionName(paramsVO.getPositionName());
        msg.setDelStatus(0);
        msgService.update(msg);
    }
    private void setLngLatDirect(Float lng,
                                 Float lat,
                                 Integer direct,double speed,Msg msg){
        msg.setPositionCoor("{\"lng\":"+lng+",\"lat\":"+lat+"}");
        msg.setDrivingSpeed(speed);
        msg.setDrivingDirection(direct+"");
    }

}
